<template>
  <div>
    <van-nav-bar title="登录" />
    <van-form @submit="onSubmit" class="form">
      <van-field
        v-model="username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[userRules[0]]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[userRules[1]]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
    <router-link class="link" to="/register">还没有账号,去注册</router-link>
  </div>
</template>

<script>
import { loginAPI } from '@/api/user'
export default {
  name: 'LoginView',
  data () {
    return {
      username: '',
      password: '',
      userRules: [
        { required: true, message: '请填写用户名' },
        { pattern: /^\S{6,20}$/, message: '请输入密码6-20位密码' }
      ]
    }
  },

  mounted () {

  },
  methods: {
    async onSubmit (values) {
      try {
        const res = await loginAPI(values)
        this.$toast.success('登录成功')
        await this.$router.push('/article')
        this.username = ''
        this.password = ''
        localStorage.setItem('mobile-token', res.data.data.token)
      } catch (e) {
        if (e.response) {
          this.$toast.fail(e.response.data.message)
        } else {
          this.$toast.fail('登录失败')
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.link{
  float: right;
  margin-right: 20px;
  font-size: 14px;
  color: red;
}

.form{
  //margin-top: 100px;
}
</style>
